package com.jim.aliceAgent.service.impl;

import com.jim.aliceAgent.entity.Reminder;
import com.jim.aliceAgent.mapper.ReminderMapper;
import com.jim.aliceAgent.service.ReminderService;
import com.jim.aliceAgent.util.StringUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.TaskScheduler;
import org.springframework.scheduling.support.CronTrigger;
import org.springframework.stereotype.Service;

import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.UUID;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ScheduledFuture;

@Service
public class ReminderServiceImpl implements ReminderService {

    @Autowired
    private TaskScheduler taskScheduler;

    @Autowired
    private ReminderMapper reminderMapper;

    // 使用 ConcurrentHashMap 存储多个任务，键为id，值为任务的 ScheduledFuture 对象
    private final ConcurrentHashMap<String, ScheduledFuture<?>> reminderMap = new ConcurrentHashMap<>();

    @Override
    public String addOrUpdateReminder(Reminder reminder) {
        // 检查reminder
        if(StringUtil.isEmpty(reminder.getUsername())) {
            return "error: username is empty";
        }
        if(!StringUtil.isValidCron(reminder.getRemindTime())) {
            return "error: remind time is invalid";
        }
        if(StringUtil.isEmpty(reminder.getContent())) {
            return "error: reminder content is empty";
        }
        if(StringUtil.isEmpty(reminder.getId())) {
            reminder.setId(UUID.randomUUID().toString());
        }
        if(reminder.getCreateTime() == null) {
            reminder.setCreateTime(new Timestamp(System.currentTimeMillis()));
        }

        // 持久化到DB
        reminderMapper.insert(reminder);

        // 停止旧reminder
        stopReminder(reminder.getId());

        // 启动新reminder
        return startReminder(reminder);
    }

    @Override
    public String startReminder(Reminder reminder) {
        if(reminderMap.containsKey(reminder.getId())) {
            return "error: reminder already exist";
        }
        ScheduledFuture<?> future = taskScheduler.schedule(() -> {
            System.out.println("reminder: " + reminder.getId() + "is running...");
        }, new CronTrigger(reminder.getRemindTime()));
        if(future == null) {
            System.out.println("reminder: " + reminder.getId() + "start failed");
            return "error: reminder start failed";
        }
        reminderMap.put(reminder.getId(), future);
        return "reminder start success";
    }

    @Override
    public String startReminderFromDB() {
        // 查询DB获取reminder
        List<Reminder> reminders = reminderMapper.selectList(null);

        // 启动
        for(Reminder reminder : reminders) {
            startReminder(reminder);
        }

        System.out.println("load reminders from database successfully");
        return "load reminders from database successfully";
    }

    @Override
    public void stopReminder(String reminderId) {
        if(!reminderMap.containsKey(reminderId)) {
            return;
        }
        ScheduledFuture<?> future = reminderMap.get(reminderId);
        future.cancel(true);
        reminderMap.remove(reminderId);
    }




}
